package study.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @author sunxuejian
 * @version 1.0
 * @date 2020/3/12 19:05
 */
@Service
public class RestWrapper {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    UserHelper userHelper;

    @Value("${jcasebe.AppCode:jcase}")
    private String appCode;

    @Value("${jcasebe.AppSecret}")
    private String appSecret;




    public <T> ResponseEntity<T> get(String url, ParameterizedTypeReference<T> responseType) {
        HttpEntity httpEntity = new HttpEntity<>(genHeaders());
        return restTemplate.exchange(url, HttpMethod.GET, httpEntity, responseType);
    }

    public <T> ResponseEntity<T> post(String url, Object reqBody, ParameterizedTypeReference<T> responseType) {
        HttpEntity reqEntity = new HttpEntity<>(reqBody, genHeaders());
        return restTemplate.exchange(url, HttpMethod.POST, reqEntity, responseType);
    }

    private HttpHeaders genHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("appId", appCode);
        Long timestamp = System.currentTimeMillis();
        headers.add("timestamp", String.valueOf(timestamp));
        headers.add("signature", getSignature(timestamp));
        headers.add("optErp", userHelper.getCurrentUserErp());
        return headers;
    }

    private String getSignature(Long timestamp) {
        //签名的明文信息，由应用编码、时间戳、和密钥顺序拼接组成
        String plainText = appCode + timestamp + appSecret;
        //生成的签名
        String signature = DigestUtils.md5DigestAsHex(plainText.getBytes());
        System.out.println("signature: " + signature);
        return signature;
    }
}
